package com.katze.boot.web.controller;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.katze.boot.common.exception.BusinessException;
import com.katze.boot.plugins.shiro.annotations.RestControllerMapping;
import com.katze.boot.plugins.shiro.annotations.RestRequestMapping;
import com.katze.boot.system.domain.City;
import com.katze.boot.system.service.CityService;
import com.katze.common.Message;
import com.katze.common.Pagination;
import com.katze.common.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestControllerMapping("city")
public class CityController extends BaseController {

    @Autowired
    private CityService cityService;

    @RestRequestMapping(permits = "city:view")
    public Message CityList(Pagination request, City city) {
        return toDataTable(this.cityService.findCitys(request, city));
    }

    @RestRequestMapping(method = RequestMethod.POST, permits = "city:add", desc = "新增城市")
    public Message addCity(@RequestBody City city) throws BusinessException {
        try {
            city.setCreateTime(new Date());
            this.cityService.createCity(city);
            return Message.ok("新增城市成功");
        } catch (Exception e) {
            throw new BusinessException("新增城市失败", e);
        }
    }

    @RestRequestMapping(method = RequestMethod.DELETE, permits = "city:delete", desc = "删除城市")
    public Message deleteCitys(String cityIds) throws BusinessException {
        try {
            String[] ids = cityIds.split(StringPool.COMMA);
            this.cityService.deleteCitys(ids);
            return Message.ok("删除城市成功");
        } catch (Exception e) {
            throw new BusinessException("删除城市失败", e);
        }
    }

    @RestRequestMapping(method = RequestMethod.PUT, permits = "city:update", desc = "修改城市")
    public Message updateDict(@RequestBody City city) throws BusinessException {
        try {
            this.cityService.updateCity(city);
            return Message.ok("修改城市成功");
        } catch (Exception e) {
            throw new BusinessException("修改城市失败", e);
        }
    }

    @RestRequestMapping(value = "export", method = RequestMethod.POST, permits = "city:export")
    public void export(Pagination request, String cityIds, @RequestBody City city, HttpServletResponse response) throws BusinessException {
        try {
            List<City> citys;
            if(StringUtils.isNotBlank(cityIds)){
                List<String> list= Arrays.asList(cityIds.split(","));
                citys = this.cityService.selectListByIds(list);
            }else{
                citys = this.cityService.findCityList(request, city);
            }
            super.downXlsx("城市信息表", citys, response);
        } catch (Exception e) {
            throw new BusinessException("导出Excel失败", e);
        }
    }


    /**
     * 生成 Excel导入模板
     */
    @RestRequestMapping(value = "template", method = RequestMethod.POST)
    public void generateImportTemplate(HttpServletResponse response) {
        // 构建数据
        List<City> list = new ArrayList<>();
//        IntStream.range(0, 20).forEach(i -> {
//            City city = new City();
//            city.setCityName("上海");
//            city.setIntroduce("沿海城市");
//            city.setLongitude("133.45");
//            city.setLatitude("87.66");
//            list.add(city);
//        });
    }

    /**
     * 导入Excel数据，并批量插入 City表
     */
    @RestRequestMapping(value = "import", method = RequestMethod.POST)
    public Message importExcels(@RequestParam("file") MultipartFile file) throws BusinessException {
        try {
            if (file.isEmpty()) {
                throw new BusinessException("导入数据为空");
            }
            String filename = file.getOriginalFilename();
            if (!StringUtils.endsWith(filename, ".xlsx")) {
                throw new BusinessException("只支持.xlsx类型文件导入");
            }
            // 开始导入操作
            long beginTimeMillis = System.currentTimeMillis();
            final List<City> data = Lists.newArrayList();
            final List<Map<String, Object>> error = Lists.newArrayList();
            /*ExcelKit.$Import(City.class).readXlsx(file.getInputStream(), new ExcelReadHandler<City>() {
                @Override
                public void onSuccess(int sheet, int row, City city) {
                    // 数据校验成功时，加入集合
                    city.setCreateTime(new Date());
                    data.add(city);
                }
                @Override
                public void onError(int sheet, int row, List<ExcelErrorField> errorFields) {
                    // 数据校验失败时，记录到 error集合
                    error.add(ImmutableMap.of("row", row, "errorFields", errorFields));
                }
            });*/
            if (!data.isEmpty()) {
                // 将合法的记录批量入库
                this.cityService.batchInsert(data);
            }
            long time = ((System.currentTimeMillis() - beginTimeMillis));
            ImmutableMap<String, Object> result = ImmutableMap.of(
                    "time", time,
                    "data", data,
                    "error", error
            );
            return Message.ok().data(result);
        } catch (Exception e) {
            throw new BusinessException("导入Excel数据失败", e);
        }
    }
}
